/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package wechat

import (
	"gitee.com/tugoer/param"
	"gitee.com/tugoer/orivil"
	"bytes"
	"io"
	"encoding/xml"
	"fmt"
	"gitee.com/tugoer/gocms/code/api/tags"
	"mime/multipart"
	"net/http"
	"encoding/json"
)

var Actions = []*orivil.Action{
	{
		Name:   "Listen WeChat Event",
		Method: "POST",
		Route:  "/",
		Handler: func(ctx *orivil.Context) {
			buf := bytes.NewBuffer(nil)
			_, err := io.Copy(buf, ctx.Request.Body)
			ctx.ErrEmergency(err)
			ctx.Request.Body.Close()
			decoder := xml.NewDecoder(buf)
			evt := &EventMessage{}
			ctx.ErrEmergency(decoder.Decode(evt))
			fmt.Println()
			fmt.Printf("Event: %+v\n", evt)
			fmt.Println()
			Dispatcher.Trigger(evt)
		},
		ApiDoc: &orivil.ApiDoc{
			Tags:    []string{tags.WeChat},
			Summary: "监听微信事件并触发本地事件",
		},
	},
	//{
	//	Name:   "Get WeChat Config",
	//	Method: "GET",
	//	Route:  "/wechat/config",
	//	Handler: func(ctx *orivil.Context) {
	//		c, err := GetWeChatConfig("default")
	//		ctx.ErrWarning(err)
	//		ctx.SendJson(c)
	//	},
	//	ApiDoc: &orivil.ApiDoc{
	//		Tags:    []string{tags.WeChat},
	//		Summary: "获取公众号配置",
	//		Responses: orivil.Responses{
	//			"200": {
	//				Description: "success",
	//				Example:     WeChatConfig{},
	//			},
	//		},
	//	},
	//},
	//{
	//	Name:   "Update WeChat Config",
	//	Method: "PUT",
	//	Route:  "/wechat/config",
	//	Params: orivil.Parameters{
	//		{
	//			In:     orivil.Form,
	//			Schema: &WeChatConfig{},
	//		},
	//	},
	//	Handler: func(ctx *orivil.Context) {
	//		p := &WeChatConfig{}
	//		ctx.WarnParse(p)
	//		err := SaveWeChatConfig("default", p)
	//		ctx.ErrWarning(err)
	//		ctx.MsgSuccess("保存成功", "")
	//	},
	//	ApiDoc: &orivil.ApiDoc{
	//		Tags:    []string{tags.WeChat},
	//		Summary: "保存公众号配置",
	//	},
	//},
	{
		Name:   "Create WeChat Menu",
		Method: "POST",
		Route:  "/wechat/menu",
		Params: orivil.Parameters{
			{
				In:     orivil.Form,
				Schema: &Menu{},
			},
		},
		Handler: func(ctx *orivil.Context) {
			// TODO: 根据管理员登陆信息获得 origin id
			env := GetAppEnv(ctx)
			token, ok := GetAccessToken(env.OriginID)
			if ok {
				p := &Menu{}
				p.JsonFile = func(field string, header *multipart.FileHeader) error {
					f, err := header.Open()
					if err != nil {
						return err
					}
					buf := bytes.NewBuffer(nil)
					_, err = io.Copy(buf, f)
					if err != nil {
						return err
					}
					f.Close()
					u := "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token.Value
					res, err := http.Post(u, "application/json", buf)
					if err != nil {
						return err
					}
					weRes := &weChatError{}
					err = json.NewDecoder(res.Body).Decode(weRes)
					res.Body.Close()
					if err != nil {
						return err
					}
					if weRes.ErrCode != 0 {
						return weRes
					} else {
						return nil
					}
				}
				ctx.WarnParse(p)
				ctx.MsgSuccess("保存成功", "")
			} else {
				ctx.MsgWarning("未获得 access_token", "")
			}
		},
		ApiDoc: &orivil.ApiDoc{
			Tags:        []string{tags.WeChat},
			Summary:     "创建公众号菜单",
			Description: "数据格式参考：[自定义菜单接口](https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013)",
		},
	},
}

type Menu struct {
	JsonFile param.FileHandler `desc:"json 格式的菜单数据" required:"数据不能为空"`
}

//type Config struct {
//	Name           string `desc:"公众号名称" required:"公众号名称不能为空"`
//	ID             string `desc:"公众号ID" required:"公众号ID不能为空"`
//	Number         string `desc:"微信号" required:"微信号不能为空"`
//	AppID          string `required:"AppID 不能为空"`
//	AppSecret      string `required:"AppSecret 不能为空"`
//	Token          string `required:"Token不能为空"`
//	EncodingAESKey string `required:"EncodingAESKey不能为空"`
//}
//
//var weChatParser = config.NewJsonParser("configs/wechat")

//func SaveWeChatConfig(file string, config interface{}) (err error) {
//	locker.Lock()
//	defer locker.Unlock()
//	return weChatParser.Create(file, config)
//}
//
//func GetWeChatConfig(file string) (config interface{}, err error) {
//	locker.Lock()
//	defer locker.Unlock()
//	err = weChatParser.ReadOrCreate(file, &config)
//	return
//}
